import os
import sys
from datetime import datetime
import json
from message_handler import (
    post_new_message_interaction,
    view_latest_messages_interaction,
    search_messages_interaction,
    view_my_posts_interaction,
    admin_interface
)
from storage_manager import (
    load_all_messages_from_file,
    save_message_to_file
)


def display_main_menu():
    """显示主菜单选项"""
    print("\n" + "=" * 40)
    print("欢迎来到匿名树洞/表白墙".center(40))
    print("=" * 40)
    print("1. 发布新消息 (匿名)")
    print("2. 查看最新消息")
    print("3. 搜索消息")
    print("4. 我的发布历史")
    print("5. 管理界面")
    print("6. 退出程序")
    print("-" * 40)


def ensure_data_directory_exists():
    """确保数据目录存在"""
    if not os.path.exists("data"):
        try:
            os.makedirs("data")
            print("数据目录已创建: data")
        except OSError as e:
            print(f"创建数据目录失败: {e}")
            sys.exit(1)


def main_loop():
    """主程序循环"""
    ensure_data_directory_exists()
    all_messages = load_all_messages_from_file()

    while True:
        display_main_menu()
        choice = input("请选择功能 (1-6): ").strip()

        try:
            if choice == "1":
                new_message = post_new_message_interaction()
                if new_message:
                    save_message_to_file(new_message)
                    all_messages.append(new_message)
                    print("消息已成功发布！")
            elif choice == "2":
                view_latest_messages_interaction(all_messages)
            elif choice == "3":
                search_messages_interaction(all_messages)
            elif choice == "4":
                view_my_posts_interaction(all_messages)
            elif choice == "5":
                admin_interface()
            elif choice == "6":
                print("感谢使用匿名树洞/表白墙，再见！")
                break
            else:
                print("无效的选择，请输入1-6之间的数字。")
        except Exception as e:
            print(f"操作出错: {e}")


if __name__ == "__main__":
    main_loop()